import { defineStore } from "pinia";
import categoryApi, { type CategoryListData } from "@/api/category";
import { ElMessage } from "element-plus";

type CategoryStateData = {
  // v-model收集的数据如果和某一项的option中value值一致 下拉框就会显示这一项option的label
  // 如果不一致 显示v-model的那个数据 展示在下拉框中
  category1Id: string | number;
  category2Id: string | number;
  category3Id: string | number;
  category1List: CategoryListData;
  category2List: CategoryListData;
  category3List: CategoryListData;
};

export const useCategoryStore = defineStore("category", {
  state: (): CategoryStateData => ({
    category1Id: '', //选中一级分类的id
    category2Id: '', //选中二级分类的id
    category3Id: '', //选中三级分类的id
    category1List: [], //一级分类列表
    category2List: [], //二级分类列表
    category3List: [], //三级分类列表
  }),
  actions: {
    async getCategory1List() {
      try {
        const res = await categoryApi.getCategory1();
        this.category1List = res;
      } catch (error) {
        ElMessage.error("获取一级分类列表失败");
      }
    },
    async getCategory2List(category1Id: number) {
      // 一级分类变化清二三级
      this.category2Id = "";
      this.category3Id = "";
      // this.category2List = []
      this.category3List = [];
      try {
        const res = await categoryApi.getCategory2(category1Id);
        this.category2List = res;
      } catch (error) {
        ElMessage.error("获取二级分类列表失败");
      }
    },
    async getCategory3List(category2Id: number) {
      // 二级分类变化清三级
      this.category3Id = "";
      // this.category3List = []
      try {
        const res = await categoryApi.getCategory3(category2Id);
        this.category3List = res;
      } catch (error) {
        ElMessage.error("获取三级分类列表失败");
      }
    },
  },
  getters: {},
});
